package com.zero.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zero.entity.FamilyMember;
import com.zero.entity.Notice;
import com.zero.mapper.FamilyMemberMapper;
import com.zero.mapper.NoticeMapper;
import com.zero.util.Constant;
import com.zero.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class NoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    public Result addNotice(Notice notice){
        log.info(notice.toString());
        if (notice == null || notice.getTitle() == null || notice.getContend() == null || notice.getValidity() == null)
            return Result.fail("公告信息不完整");

        notice.setCreateDate(new Date());
        int row = noticeMapper.add(notice);
        if (row == 1)
            return Result.ok("添加成功");
        return Result.fail("添加失败");
    }

    @Transactional
    public Result deleteNotice(String ids){
        if (ids == null)
            return Result.fail("获取不到删除的记录信息");

        String[] idSet = ids.split(",");
        int row = 0;
        for (String id : idSet) {
            row += noticeMapper.delete(Integer.parseInt(id));
        }

        return Result.ok("成功删除"+ row +"条记录");
    }

    public Result updateNotice(Notice notice){
        if (notice == null || notice.getId() == null)
            return Result.fail("获取不到修改的信息");

        int row = noticeMapper.update(notice);
        if (row == 1)
            return Result.ok("更新公告信息成功");
        return Result.fail("更新公告信息失败");
    }

    /**
     * 获取系统公告列表（带分页）
     * @param notice
     * @return
     */
    public Result selectSystemNotice(Notice notice){
        if (notice == null)
            return Result.fail("获取不到具体的查询信息");
        notice.setType(0);

        //设置分页查询信息
        if (notice.getPage() != null){
            if (notice .getLimit() != null)
                PageHelper.startPage(notice.getPage(), notice.getLimit());
            else
                PageHelper.startPage(notice.getPage(), 10);
        }else{
            PageHelper.startPage(1, 10);
        }

        List<Notice> result = noticeMapper.select(notice);
        PageInfo pageInfo = new PageInfo(result);
        return Result.ok(result, pageInfo.getTotal());
    }

    /**
     * 获取家庭公告列表（带分页）
     * @param notice
     * @param request
     * @return
     */
    public Result selectFamilyNotice(Notice notice, HttpServletRequest request){
        if (notice == null)
            return Result.fail("获取不到具体的查询信息");

        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到用户信息");
        familyMember = familyMemberMapper.selectById(familyMember.getId());

        notice.setFamilyId(familyMember.getFamilyId());
        //设置分页查询信息
        if (notice.getPage() != null){
            if (notice .getLimit() != null)
                PageHelper.startPage(notice.getPage(), notice.getLimit());
            else
                PageHelper.startPage(notice.getPage(), 10);
        }else{
            PageHelper.startPage(1, 10);
        }

        List<Notice> result = noticeMapper.select(notice);
        PageInfo pageInfo = new PageInfo(result);
        return Result.ok(result, pageInfo.getTotal());
    }

    /**
     * 查询系统显示的公告
     * @return
     */
    public Result selectSystemNotice(){
        Notice param = new Notice();
        param.setType(0);
        List<Notice> notices = noticeMapper.select(param);
        List<Notice> result = filterValidityNotice(notices);
        return Result.ok("查询成功", result);
    }

    /**
     * 查询家庭显示的公告
     * @param request
     * @return
     */
    public Result selectFamilyNotice(HttpServletRequest request){
        FamilyMember familyMember = (FamilyMember) request.getAttribute("familyMember");
        if (familyMember == null || familyMember.getId() == null)
            return Result.fail("获取不到用户信息");
        familyMember = familyMemberMapper.selectById(familyMember.getId());

        //查找所有的系统公告和家庭公告
        Notice param = new Notice();
//        param.setType(0);
        param.setFamilyId(familyMember.getFamilyId());
        List<Notice> notices = noticeMapper.select(param);

        //过滤公告
        List<Notice> result = filterValidityNotice(notices);

        return Result.ok("查询成功", result);
    }

    /**
     * 过滤有效期内的公告
     * @param notices
     * @return
     */
    private List<Notice> filterValidityNotice(List<Notice> notices){

        if (notices == null)
            return null;

        //获得当前时间
        Date now = new Date();
        List<Notice> result = new ArrayList<>();

        //让（公告创建时间点 + 有效时长的毫秒数）与目前的时间点做比较，若大于则说明公告还没过期，否则过期
        for (Notice notice : notices) {
            Date createDate = notice.getCreateDate();
            long validity = createDate.getTime() + (long)Constant.MILLISECOND_OF_DAY * notice.getValidity();
//            log.info(notice.getCreateDate().getTime()+ ": " + (Constant.MILLISECOND_OF_DAY * notice.getValidity()) + "----" + now.getTime());
            if (validity > now.getTime()){
                result.add(notice);
            }
        }

        return result;
    }

}
